jQuery(function($){
	// Create variables (in this scope) to hold the API and image size
	var img_src;
	
    var jcrop_api,
        boundx,
        boundy,
        xsize,
        ysize;
        
     // Grab some information about the preview pane
	$preview = $('#preview-pane'),
	$pcnt = $('#preview-pane .preview-container'),
	$pimg = $('#preview-pane .preview-container img');
	
    $('#select_cover').click(function() {
    	generateCarousel(window.current_post_id);
        $('#cover_select_modal').modal('show');
        $('#cover_select_carousel').carousel({
            interval: false
        });
    });
    
    $('#submit_cover').click(submit);

    function updatePreview(c)
    {
      if (parseInt(c.w) > 0)
      {
        var rx = xsize / c.w;
        var ry = ysize / c.h;

        $pimg.css({
          width: Math.round(rx * boundx) + 'px',
          height: Math.round(ry * boundy) + 'px',
          marginLeft: '-' + Math.round(rx * c.x) + 'px',
          marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
      }
    };
    
    function gen_carousel_indicator(count) {
        var html = '';
        for (i = 0; i < count; i++) {
            html += '<li data-target="#cover_select_carousel" data-slide-to="' + i + '"';
            if (i == 0) {
                html += 'class="active"></li>';
            } else {
                html += '></li>';
            }
        }
        return html;
    }
    
    function generateCarousel(post_id) {
    	$.post('post/select_post_cover_carousel/'+post_id, {
        }, function(carousel) {
            $.get('assets/templates/slide_cover_carousel.html', function(html) {
                var carousel_html = '';
                for (id in carousel) {
                    var view = {
                        photo_id: carousel[id].photo_id,
                        location: carousel[id].location,
                        width: carousel[id].width,
                        height: carousel[id].height
                    };
                    carousel_html += Mustache.render(html, view);
                }
                $('#cover_select_carousel .carousel-inner').empty().html(carousel_html);
                $('#cover_select_carousel .carousel-inner .item:first-child').addClass('active');
                $('#cover_select_carousel .carousel-inner').children('.item').click(function() {
                	start_cropping($(this));
                });     
            });    
            var indicator = gen_carousel_indicator(carousel.length);
            $('#cover_select_carousel .carousel-indicators').empty().html(indicator);
        }, 'json');    	
    }
    
    function start_cropping($selected_cover_item) {
    	img_src = $selected_cover_item.find('img').first().attr('src');
    	$('#cover_select_modal').modal('hide');
    	$('#step2 img').attr('src', img_src);
    	enable_jcrop();
    	$('#step1').fadeOut(300);
    	$('#step2').delay(300).fadeIn(300);
    	$('#step3').delay(300).fadeIn(300);
    }
    
    function enable_jcrop() {
    	xsize = $pcnt.width(),
    	ysize = $pcnt.height();
    	
        console.log('init',[xsize,ysize]);
        $('#target').Jcrop({
          onChange: updatePreview,
          onSelect: updatePreview,
          aspectRatio: xsize / ysize,
          addClass: 'crop-border',
          boxWidth: 850,
          boxHeight: 638
        },function(){
          // Use the API to get the real image size
          var bounds = this.getBounds();
          
          boundx = bounds[0];
          boundy = bounds[1];
          // Store the API in the jcrop_api variable
          jcrop_api = this;

          // Move the preview into the jcrop container for css positioning
          $preview.appendTo(jcrop_api.ui.holder);
        });
    }
    
    function submit() {
    	select = jcrop_api.tellSelect();
    	$.post('post/submit_post_cover', {
    		post_id: window.current_post_id,
    		location: img_src,
    		width: select.w,
    		height: select.h,
    		x_axis: select.x,
    		y_axis: select.y
        }, function(data, textStatus) {
        	if( data.code = 1) {
        		$('#resultimage').attr('src', data.src);
	        	$('#step2').fadeOut(300);
	        	$('#step3').fadeOut(300);
	        	$('#result').delay(300).fadeIn(300);
        	}
        }, 'json');
    	return false;
    }
});
    